package com.zbkj.crmeb.store.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.utils.StoreProductMerUtil;
import com.zbkj.crmeb.chant.model.ChannelMerchant;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.store.request.*;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.common.CommonPage;
import com.crmeb.core.common.CommonResult;
import com.common.PageParamRequest;
import com.github.pagehelper.PageInfo;
import com.utils.PriceUtil;
import com.zbkj.crmeb.chant.service.IChannelProductService;
import com.zbkj.crmeb.enums.ProductTypeEnum;
import com.zbkj.crmeb.store.model.StoreProduct;
import com.zbkj.crmeb.store.response.StoreProductAttrValueResponse;
import com.zbkj.crmeb.store.response.StoreProductNormResponse;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.store.response.StoreProductTabsHeader;
import com.zbkj.crmeb.store.service.StoreBrandService;
import com.zbkj.crmeb.store.service.StoreCartService;
import com.zbkj.crmeb.store.service.StoreProductService;
import com.zbkj.crmeb.system.service.SystemConfigService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 商品表 前端控制器
 *
 * @author muyu
 * @date 2020-10-13
 */
@RestController
@RequestMapping("api/admin/store/product")
@Api(tags = "后台商品") //配合swagger使用
public class StoreProductController {
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    private StoreProductService storeProductService;
    @Autowired
    private StoreCartService storeCartService;
    @Autowired
    SystemConfigService systemConfigService;
    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private IChannelProductService channelProductService;
    @Autowired
    private IChannelMerchantService channelMerchantService;

    @Autowired
    private StoreProductMerUtil storeProductMerUtil;

    /**
     * 分页显示商品表(商户自建商品)
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "自建商品分页列表")
    @RequestMapping(value = "/inside/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<StoreProductResponse>> getInsideList(@Validated StoreProductSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        request.setIsEurope(ProductTypeEnum.INSIDE.getCode());

        PageInfo<StoreProductResponse> pageInfo = storeProductService.getList(request, pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 分页显示商品表(供应商商品)
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "云仓商品分页列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public CommonResult<CommonPage<StoreProductResponse>> getList(@Validated StoreProductSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        List<Integer> isNotEurope = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
        request.setIsNotEurope(isNotEurope);

        PageInfo<StoreProductResponse> pageInfo = storeProductService.getList(request, pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 分页显示商品表(供应商商品)
     *
     * @param request          搜索条件
     * @param pageParamRequest 分页参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "供应商商品分页列表")
    @RequestMapping(value = "/listV2", method = RequestMethod.GET)
    public CommonResult<CommonPage<StoreProductResponse>> getListV2(@Validated StoreProductSearchRequest request, @Validated PageParamRequest pageParamRequest) {
        List<Integer> isNotEurope = Arrays.asList(ProductTypeEnum.INSIDE.getCode());
        request.setIsNotEurope(isNotEurope);

        PageInfo<StoreProductResponse> pageInfo = storeProductService.getListV2(request, pageParamRequest);
        return CommonResult.success(CommonPage.restPage(pageInfo));
    }

    /**
     * 商品sku列表
     *
     * @param @param  request
     * @param @param  pageParamRequest
     * @param @return
     * @return CommonResult<CommonPage < StoreProductResponse>>
     * @throws
     * @Description:
     * @author daigb
     */
    @ApiOperation(value = "sku分页列表")
    @GetMapping("/sku/page")
    public CommonResult<PageInfo<StoreProductAttrValueResponse>> selectSkuPage(@Validated StoreProductSearchRequest request) {
        PageInfo<StoreProductAttrValueResponse> pageInfo = storeProductService.selectSkuPage(request);
        return CommonResult.success(pageInfo);
    }

    /**
     * 新增商品表
     *
     * @param storeProductRequest 新增参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "新增")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public CommonResult<String> save(@RequestBody @Validated StoreProductRequest storeProductRequest) {

        //sourceCost
        storeProductRequest.setSourceCost(storeProductRequest.getCost());
        if (storeProductService.save(storeProductRequest)) {
            //获取品牌id
            Integer brandId = storeProductRequest.getBrandId();

            //处理品牌-在线商品数量
            storeBrandService.showProductCount(brandId, true);

            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @PutMapping("/batch-is-show")
    @ApiOperation("批量上架/下架")
    public CommonResult<Object> batchEnabled(@RequestBody @Validated BatchEnabledRequest vo) {
        return CommonResult.success(storeProductService.batchEnabled(vo));
    }

    /**
     * 验证条形码
     *
     * @param barCode
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "验证条形码")
    @RequestMapping(value = "/verify-barcode/{barCode}", method = RequestMethod.GET)
    public CommonResult<String> verifyBarCode(@PathVariable String barCode) {
        //验证barcode - 条形码
        if (StringUtils.isEmpty(barCode)) {
            return CommonResult.failed("条形码：" + barCode + " 为空，请重新输入！");
        }
        if (!StringUtils.isNumeric(barCode)) {
            return CommonResult.failed("条形码：" + barCode + " 必须为数字，请重新输入！");
        }
        if (storeProductService.verifyBarCode(barCode)) {
            return CommonResult.failed("条形码：" + barCode + " 已存在，请重新输入！");
        }
        return CommonResult.success();
    }

    /**
     * 删除商品表
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "删除")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public CommonResult<String> delete(@RequestBody @PathVariable Integer id) {
        if (storeProductService.deleteProduct(id)) {
            //        if(storeProductService.removeById(id)){
            storeCartService.productStatusNotEnable(id);
            StoreProduct storeProduct = storeProductService.getById(id);
            if (ObjectUtils.isNotEmpty(storeProduct)) {
                //处理品牌-在线商品数量
                storeBrandService.showProductCount(storeProduct.getBrandId(), false);
                //更新关联的渠道商品
                channelProductService.updateProductByBarCode(storeProduct.getBarCode());
            }
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 恢复已删除商品表
     *
     * @param id Integer
     * @author Stivepeim
     * @since 2020-08-28
     */
    @ApiOperation(value = "恢复商品")
    @RequestMapping(value = "/restore/{id}", method = RequestMethod.GET)
    public CommonResult<String> restore(@RequestBody @PathVariable Integer id) {
        if (storeProductService.reStoreProduct(id)) {
            //            storeCartService.productStatusNotEnable(id);
            StoreProduct storeProduct = storeProductService.getById(id);
            if (ObjectUtils.isNotEmpty(storeProduct)) {
                //处理品牌-在线商品数量
                storeBrandService.showProductCount(storeProduct.getBrandId(), true);
            }
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 修改商品表
     *
     * @param storeProductRequest 修改参数
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "修改")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public CommonResult<String> update(@RequestBody @Validated StoreProductRequest storeProductRequest) {

        //sourceCost
        storeProductRequest.setSourceCost(storeProductRequest.getCost());
        if (storeProductService.update(storeProductRequest)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 查询商品表信息
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "自建商品详情")
    @RequestMapping(value = "/inside/info/{id}", method = RequestMethod.GET)
    public CommonResult<StoreProductResponse> insideInfo(@PathVariable Integer id) {
        StoreProductResponse storeProductResponse = storeProductService.getByProductId(id);
        return CommonResult.success(storeProductResponse);
    }

    /**
     * 查询商品表信息
     *
     * @param id Integer
     * @author Mr.Zhang
     * @since 2020-05-27
     */
    @ApiOperation(value = "云仓商品详情")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    public CommonResult<StoreProductNormResponse> info(@PathVariable Integer id) {
        StoreProductNormResponse storeProductResponse = storeProductService.getSupplierByProductId(id);
        return CommonResult.success(storeProductResponse);
    }

    /**
     * 商品tabs表头数据
     *
     * @return
     */
    @ApiOperation(value = "云仓商品表头数量")
    @RequestMapping(value = "/tabs/headers", method = RequestMethod.GET)
    public CommonResult<List<StoreProductTabsHeader>> getTabsHeader() {
        return CommonResult.success(storeProductService.getTabsHeader(2));
    }

    /**
     * 商品tabs表头数据
     *
     * @return
     */
    @ApiOperation(value = "自建商品表头数量")
    @RequestMapping(value = "/inside/tabs/headers", method = RequestMethod.GET)
    public CommonResult<List<StoreProductTabsHeader>> getInsideTabsHeader() {
        return CommonResult.success(storeProductService.getTabsHeader(1));
    }

    /**
     * 上架
     *
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "上架")
    @RequestMapping(value = "/putOnShell/{id}", method = RequestMethod.GET)
    public CommonResult<String> putOn(@PathVariable Integer id) {
        StoreProduct storeProduct = new StoreProduct();
        storeProduct.setId(id);
        storeProduct.setIsShow(true);
        storeProduct.setTmall(false);
        if (storeProductService.updateById(storeProduct)) {
            //处理品牌-在线商品数量
            storeBrandService.showProductCount(storeProduct.getBrandId(), true);
            //更新关联的渠道商品
            channelProductService.updateProductByBarCode(storeProduct.getBarCode());
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 下架
     *
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @ApiOperation(value = "下架")
    @RequestMapping(value = "/offShell/{id}", method = RequestMethod.GET)
    public CommonResult<String> offShell(@PathVariable Integer id) {
        StoreProduct storeProduct = storeProductService.getById(id);
        storeProduct.setIsShow(false);
        storeProduct.setTmall(true);
        if (storeProductService.updateById(storeProduct)) {
            storeCartService.productStatusNotEnable(id);
            //处理品牌-在线商品数量
            storeBrandService.showProductCount(storeProduct.getBrandId(), false);
            //更新关联的渠道商品
            channelProductService.updateProductByBarCode(storeProduct.getBarCode());
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    /** 方法弃用
     * 虚拟销量
     * @param id integer id
     * @author Mr.Zhang
     * @since 2020-05-06
     */
	/*@ApiOperation(value = "虚拟销量")
	@RequestMapping(value = "/ficti/{id}/{num}", method = RequestMethod.GET)
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "id", dataType = "int", required = true), @ApiImplicitParam(name = "num", value = "数值", dataType = "int", required = true), })
	public CommonResult<String> sale(@PathVariable Integer id, @PathVariable Integer num) {
	    StoreProduct storeProduct = storeProductService.getById(id);
	    storeProduct.setFicti(num);
	    if (storeProductService.updateById(storeProduct)) {
	        return CommonResult.success();
	    } else {
	        return CommonResult.failed();
	    }
	}*/

    //    /**
    //     * 修改商品表
    //     * @param id integer id
    //     * @param num integer 排序值
    //     * @author Mr.Zhang
    //     * @since 2020-05-06
    //     */
    //    @ApiOperation(value = "排序数字")
    //    @RequestMapping(value = "/sort", method = RequestMethod.GET)
    //    @ApiImplicitParams({
    //            @ApiImplicitParam(name = "id", value = "id", dataType = "Integer", required = true),
    //            @ApiImplicitParam(name = "num", value = "数值", dataType = "Integer", required = true),
    //    })
    //    public CommonResult<String> sort(@RequestParam(value = "id") Integer id, @RequestParam(value = "num") Integer num){
    //        StoreProduct storeProduct = storeProductService.getById(id);
    //        storeProduct.setSort(num);
    //        if(storeProductService.updateById(storeProduct)){
    //            return CommonResult.success();
    //        }else{
    //            return CommonResult.failed();
    //        }
    //    }

    /**
     * 库存变动
     *
     * @param request StoreProductStockRequest 参数
     * @author Mr.Zhang
     * @since 2020-05-19
     */
    @ApiOperation(value = "库存变动")
    @RequestMapping(value = "/stock", method = RequestMethod.GET)
    public CommonResult<String> stock(@Validated StoreProductStockRequest request) {
        if (storeProductService.stockAddRedis(request)) {
            return CommonResult.success();
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "导入商品")
    @RequestMapping(value = "/importProduct", method = RequestMethod.POST)
    @ApiImplicitParams({@ApiImplicitParam(name = "form", value = "导入平台1=淘宝，2=京东，3=苏宁，4=拼多多, 5=天猫", dataType = "int", required = true), @ApiImplicitParam(name = "url", value = "URL", dataType = "String", required = true),})
    public CommonResult<StoreProductRequest> importProduct(@RequestParam @Valid int form, @RequestParam @Valid String url) throws IOException, JSONException {

        //        String id = UrlUtil.getParamsByKey(url, "id");
        //        if(StringUtils.isBlank(id)){
        //            return CommonResult.failed("url 中未找到有效参数");
        //        }
        StoreProductRequest productRequest = storeProductService.importProductFromUrl(url, form);
        return CommonResult.success(productRequest);
    }

    /**弃用
     * 设置是否参加活动
     * @param productId
     * @param isPromoter
     * @return
     */
	/*@ApiOperation(value = "设置是否参加活动")
	@RequestMapping(value = "/setIsPromoter", method = RequestMethod.POST)
	public CommonResult<String> setIsPromoter(@RequestParam Integer productId, @RequestParam Boolean isPromoter) {
	    if (storeProductService.updateIsPromoter(productId, isPromoter)) {
	        return CommonResult.success("更新成功");
	    } else {
	        return CommonResult.failed("更新失败");
	    }
	}*/

    /**
     * 设置小编推荐
     *
     * @param productId
     * @param isBest
     * @return
     */
    @ApiOperation(value = "设置小编推荐")
    @RequestMapping(value = "/setIsBest", method = RequestMethod.POST)
    public CommonResult<String> setIsBest(@RequestParam Integer productId, @RequestParam Boolean isBest) {
        if (storeProductService.updateIsBest(productId, isBest)) {
            return CommonResult.success("更新成功");
        } else {
            return CommonResult.failed("更新失败");
        }
    }

    /**
     * 修改商品编码
     *
     * @param storeProductRequest 修改参数
     * @author cdm
     * @since 2023-07-26
     */
    @ApiOperation(value = "修改商品编码")
    @RequestMapping(value = "/updateKeyword", method = RequestMethod.POST)
    public CommonResult<String> updateKeyword(@RequestBody StoreProductRequest storeProductRequest) {
        if (null == storeProductRequest.getId()) return CommonResult.failed("id不能为空");
        if (StrUtil.isEmpty(storeProductRequest.getKeyword())) return CommonResult.failed("编码不能为空");
        StoreProduct storeProduct = new StoreProduct();
        storeProduct.setId(storeProductRequest.getId());
        storeProduct.setKeyword(storeProductRequest.getKeyword());
        storeProductService.updateKeyword(storeProduct);
        return CommonResult.success();
    }


    /**
     * 修改商品视频
     *
     * @param storeProductRequest 修改参数
     * @author cdm
     * @since 2023-07-26
     */
    @ApiOperation(value = "修改商品视频")
    @RequestMapping(value = "/updateVideo", method = RequestMethod.POST)
    public CommonResult<String> updateVideo(@RequestBody StoreProductRequest storeProductRequest) {
        if (null == storeProductRequest.getId()) return CommonResult.failed("id不能为空");
        storeProductService.updateVideo(storeProductRequest);
        return CommonResult.success();
    }

    @ApiOperation(value = "刷新商品索引")
    @RequestMapping(value = "/updateIndex", method = RequestMethod.GET)
    public CommonResult<String> updateIndex() {
//        ThreadUtil.execute(() -> {
//            productSearchService.updateData();
//        });
        return CommonResult.success("开始刷新");
    }

    @ApiOperation(value = "实时更新商品")
    @PostMapping("/update/real-time")
    public CommonResult<Object> updateRealTime(@ApiParam(value = "商品id", required = true) @RequestParam Integer productId) {
        Object o = storeProductService.updateRealTime(productId);
        return Objects.isNull(o) ? CommonResult.failed() : CommonResult.success(o);
    }

    @PutMapping("/transfer/cloud/audit")
    @ApiOperation("审核自建商品转云仓")
    public CommonResult<Object> auditTransferCloud(@RequestBody @Validated BestEnabledRequest vo) {
        if (CollectionUtils.isEmpty(vo.getProductIdList())) {
            return CommonResult.validateFailed("商品id不能为空");
        }
        return storeProductService.auditTransferCloud(vo) ? CommonResult.success() : CommonResult.failed();
    }

    @ApiOperation(value = "商户商品表处理 ok")
    @RequestMapping(value = "/makeStoreProductMerColumns", method = RequestMethod.POST)
    public CommonResult<String> makeStoreProductMerColumns(HttpServletRequest servletRequest) {

        List<ChannelMerchant> merchantList = channelMerchantService.list(Wrappers.<ChannelMerchant>lambdaQuery()
                .eq(ChannelMerchant::getIsDel, 0)
                .select(ChannelMerchant::getId));

        merchantList.forEach(mer -> {

            Boolean flg = storeProductMerUtil.makeColumnsTwo(mer.getId());

        });

        return CommonResult.success("处理结束！");
    }
}
